package com.daykw.wenshu.task;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.daykw.wenshu.config.NutzDaoConfig;
import com.daykw.wenshu.http.HttpBase;
import com.daykw.wenshu.model.CourtUrl;
import com.daykw.wenshu.model.SearchSubDailyUrl;
import com.daykw.wenshu.utils.Const;
import com.daykw.wenshu.utils.SpringContextHolder;

public class ListDailySubUrlJob extends Thread {

	private static Logger logger = Logger.getLogger(ListDailySubUrlJob.class);
	private NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

	public ListDailySubUrlJob() {
		if (StringUtils.isNotEmpty(Const.Node)) {
			dao.update(SearchSubDailyUrl.class, Chain.make("status", 0),
					Cnd.where("status", "=", 1).and("node", "=", Const.Node));
		} else {
			dao.update(SearchSubDailyUrl.class, Chain.make("status", 0), Cnd.where("status", "=", 1));
		}

	}

	public Date getPreDay() {
		Calendar calendar = Calendar.getInstance();

		calendar.add(Calendar.DAY_OF_MONTH, -2);
		Date date = calendar.getTime();
		return date;
	}

	@Override
	public void run() {
		List<SearchSubDailyUrl> ds = null;
		if (StringUtils.isNotEmpty(Const.Node)) {
			ds = dao.query(SearchSubDailyUrl.class,
					Cnd.where("status", "=", 0).and("node", "=", Const.Node).limit(1, 5).asc("id"));
		} else {
			ds = dao.query(SearchSubDailyUrl.class, Cnd.where("status", "=", 0).limit(1, 5).asc("id"));
		}

		for (SearchSubDailyUrl search : ds) {
			this.snatch(search, dao);
		}

	}

	public void snatch(SearchSubDailyUrl search, NutDao dao) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		dao.update(SearchSubDailyUrl.class, Chain.make("status", 1), Cnd.where("id", "=", search.getId()));
		HttpBase http = new HttpBase();
		try {
			Const.stopFirefox();
			WebDriver wb = http.getFirefox();
			String url = search.getUrl();
			wb.get(url);

			try {
				WebDriverWait wait = new WebDriverWait(wb, 30);
				wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.dataItem")));
			} catch (Exception e) {
				// e.printStackTrace();
			}

			JavascriptExecutor js = (JavascriptExecutor) wb;
			// 获取网页高度，用于滚动到底部，防止仅加载一部分数据

			wb.manage().window().maximize();
			try {
				js.executeScript("scrollTo(0,30000)");
			} catch (Exception E) {

			}
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			WebElement resultList = wb.findElement(By.id("resultList"));
			WebElement span_datacount = wb.findElement(By.id("span_datacount"));
			String datacount = span_datacount.getText();
			String html = resultList.getText();
			if (html.contains("无符合条件的数据")) {
				dao.update(SearchSubDailyUrl.class, Chain.make("status", 2).add("total", datacount),
						Cnd.where("id", "=", search.getId()));
				return;
			} else {
				try {
					List<WebElement> dataItems = wb.findElements(By.cssSelector("div.dataItem"));
					if (dataItems.size() == 0) {
						dao.update(SearchSubDailyUrl.class, Chain.make("status", 3),
								Cnd.where("id", "=", search.getId()));
						return;
					}
				} catch (Exception e) {
					dao.update(SearchSubDailyUrl.class, Chain.make("status", 3), Cnd.where("id", "=", search.getId()));
					return;
				}
			}

			int totalCount = Integer.parseInt(datacount);

			dao.update(SearchSubDailyUrl.class, Chain.make("total", datacount), Cnd.where("id", "=", search.getId()));

			int pageSize = 10;
			int maxPage = 1;

			if (totalCount % pageSize == 0) {
				maxPage = totalCount / pageSize;
			} else {

				if (totalCount <= pageSize) {
					maxPage = 1;
				} else {
					maxPage = (totalCount / pageSize) + 1;
				}

			}

			if (maxPage >= 20) {
				maxPage = 20;
			}
			int p = search.getPage();
			if (p >= 3) {

				int b = 2;

				List<WebElement> as = wb.findElements(By.cssSelector("div.pageNumber a"));
				for (WebElement we : as) {
					String click = we.getText();

					if (p > 10) {
						if (click.equals("10")) {
							we.click();

							b = 10;
							try {
								TimeUnit.SECONDS.sleep(6);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							break;
						}
					} else {
						if (click.equals(p + "")) {
							we.click();
							b = p;
							try {
								TimeUnit.SECONDS.sleep(6);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							break;
						}
					}

				}

				for (int i = b; i < p; i++) {
					try {
						WebDriverWait wait1 = new WebDriverWait(wb, 10);
						wait1.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a.next")));

						wb.findElement(By.cssSelector("a.next")).click();

						TimeUnit.SECONDS.sleep(6);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			try {
				TimeUnit.SECONDS.sleep(6);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (int i = p; i <= maxPage; i++) {
				logger.info("开始获取docid");
				String ids = (String) ((JavascriptExecutor) wb).executeScript(
						"function getIds(){var items =  document.querySelectorAll(\"div.dataItem\");var ids = new Array();var len = items.length;	for(var i=0;i<len;i++){ var key = items[i].getAttribute(\"key\");var unzipid = unzip(key);var realid = com.str.Decrypt(unzipid);ids[i]=realid;} var str = ids.join(',');return str;};  return  getIds();");
				logger.info("获取docid完毕");
				String[] idList = ids.split(",");
				if (idList == null || idList.length == 0) {
					dao.update(SearchSubDailyUrl.class, Chain.make("status", 5), Cnd.where("id", "=", search.getId()));
					return;
				}
				List<WebElement> dataItems = wb.findElements(By.cssSelector("div.dataItem"));
				// Elements dataItems = doc.select("div.dataItem");
				String date = df.format(new Date());
				for (int k = 0; k < dataItems.size(); k++) {
					WebElement dataItem = dataItems.get(k);
					String title = dataItem.getAttribute("title");
					String casecourt = dataItem.getAttribute("casecourt");
					String casenumber = dataItem.getAttribute("casenumber");
					String judgedate = dataItem.getAttribute("judgedate");
					String trial_round = null;
					String case_type = null;
					List<WebElement> ajlx_lables = dataItem.findElements(By.cssSelector("div.ajlx_lable"));

					if (ajlx_lables != null && ajlx_lables.size() > 0) {
						trial_round = ajlx_lables.get(0).getText();
						if (ajlx_lables.size() > 1) {
							case_type = ajlx_lables.get(1).getText();
						}
					}

					String docid = idList[k];
					String docUrl = "http://wenshu.court.gov.cn/content/content?DocID=" + docid + "&KeyWord=";
					CourtUrl cour = new CourtUrl();
					cour.setCase_name(title);
					cour.setCase_number(casenumber);
					cour.setCourt_name(casecourt);
					cour.setCase_type(case_type);
					cour.setCreate_time(new Date());
					cour.setDoc_id(docid);
					cour.setJudgement_date(judgedate);
					cour.setPublish_date(search.getStart_date());
					cour.setTrial_round(trial_round);
					cour.setUrl(docUrl);
					cour.setHandled("P");
					cour.setCity(search.getCity());
					cour.setCourt_level(search.getCourt_level());
					cour.setCase_keyword(search.getCase_type());
					cour.setCreate_date(Integer.parseInt(date));
					try {
						dao.fastInsert(cour);
					} catch (Exception e) {
						logger.error("插入重复:" + docid + ",page:" + i);
					}
					// 选取原来的句柄，回到原来页面

				}
				dao.update(SearchSubDailyUrl.class, Chain.make("page", (i + 1)), Cnd.where("id", "=", search.getId()));
				logger.info("完成" + search.getStart_date() + " ,第:" + i + "页下载");
				if (i == maxPage) {
					logger.info("完成" + search.getStart_date() + " ,第:" + i + "页下载");
					break;
				}
				WebDriverWait wait1 = new WebDriverWait(wb, 5);
				wait1.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a.next")));

				wb.findElement(By.cssSelector("a.next")).click();
				try {
					TimeUnit.SECONDS.sleep(5);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					WebDriverWait wait = new WebDriverWait(wb, 30);
					wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.dataItem")));
				} catch (Exception e) {
					e.printStackTrace();
				}

				dao.update(SearchSubDailyUrl.class, Chain.make("page", (i + 1)), Cnd.where("id", "=", search.getId()));
				logger.info("翻页完成 ,第:" + (i + 1) + "页");
				try {
					TimeUnit.SECONDS.sleep(4);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			dao.update(SearchSubDailyUrl.class, Chain.make("status", 2), Cnd.where("id", "=", search.getId()));
			logger.info("#########完成" + search.getStart_date() + " ,全部下载#########");
		} catch (IOException e) {
			dao.update(SearchSubDailyUrl.class, Chain.make("status", 3), Cnd.where("id", "=", search.getId()));
			logger.error("", e);
		}
	}

}
